import React,{useState,useEffect,useMemo} from 'react'
import $http from '../api/http'
export default function ShopcartList() {
  const [list,setList]=useState([])
  /*
    获取购物车中的信息
  */
  const getShopcartListApi=async()=>{
    const {data:{data}}=await $http.shopcart.getShopcartList()
    console.log(data);
    setList(data)
  }
  const changeNum=async data=>{
    const {data:{code}}=await $http.shopcart.changeNum(data)
    if(code){
        getShopcartListApi()
    }
  }
  const changeNum1=(_id,index,n)=>{
    list[index].num=~~n
    setList([...list])
    // console.log('_id',_id);
    // console.log('n',n);
    // for(let i=0;i<list.length;i++){
    //     if(list[i]._id==_id){
    //         list[i].num=~~n
    //     }
    // }
    // setList([...list])
  }
  const changeInputNum=async(_id,n)=>{
     const {data:{code}}=await $http.shopcart.changeNumByInput({_id,n})
     if(code){
        getShopcartListApi()
     }
  }
  const checkItem=async(_id)=>{
    const {data:{code}}=await $http.shopcart.changeCheckStatus(_id)
    if(code){
        getShopcartListApi()
    }
  }
  useEffect(()=>{
    getShopcartListApi()
  },[])
  //使用useMemo完成计算总价
  const total=useMemo(()=>{
    return list.filter(item=>item.checked).reduce((pre,cur)=>pre+cur.price*cur.num,0)
  },[list])



  return (
    <div>
        <h2>购物车</h2>
        <table>
            <thead>
                <tr>
                    <th>编号:</th>
                    <th>名称</th>
                    <th>价格</th>
                    <th>数量</th>
                    <th>小计</th>
                </tr>
            </thead>
            <tbody>
                {
                    list.map((item,index)=><tr key={item._id}>
                        <td>
                            <input type="checkbox" 
                             checked={item.checked} 
                             onChange={()=>{checkItem(item._id)}}/>
                        </td>
                        <td>{item.name}</td>
                        <td>{item.price}</td>
                        <td>
                            <button onClick={()=>{changeNum({_id:item._id,n:-1})}}>-</button>
                            <input type="text" 
                                   value={item.num} 
                                   onChange={(e)=>{changeNum1(item._id,index,e.target.value)}}
                                   onBlur={(e)=>{changeInputNum(item._id,e.target.value)}}/>
                            <button onClick={()=>{changeNum({_id:item._id,n:1})}}>+</button>
                        </td>
                        <td>{(item.price*item.num).toFixed(2)}</td>
                    </tr>)
                }
                <tr>
                    <td colSpan={5}>总价:{total}</td>
                </tr>
            </tbody>
        </table>
    </div>
  )
}
